<template>
  <div>
    <van-swipe class="swipe-container" :loop="false">
      <van-swipe-item v-for="page in 1" :key="page">
        <van-grid :column-num="4" :border="false">
          <van-grid-item
            v-for="(department, index) in departments"
            :key="index"
            @click="goToDoctorSelector(department)"
          >
            <template #icon>
              <van-icon name="user-o" color="#4395ff" size="24" />
            </template>
            <template #text>
              <span class="grid-text">{{ department }}</span>
            </template>
          </van-grid-item>
        </van-grid>
      </van-swipe-item>
    </van-swipe>

    <!-- 加载状态 -->
    <van-empty v-if="loading" description="加载中..." />
    <van-empty v-if="!loading && departments.length === 0" description="暂无科室数据" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from "../../stores/user.js";
import { getAllDepartmentNames } from "../../api/department/departmentRequest.js";
import { useRouter } from "vue-router";
import { showToast } from 'vant';

const userStoreAPI = useUserStore();
const router = useRouter();
const departments = ref([]);
const loading = ref(true);

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const res = await getAllDepartmentNames();
    if (res.success) {
      departments.value = res.data;
    } else {
      showToast(res.errMsg || '获取科室列表失败');
    }
  } catch (error) {
    console.error("获取科室列表失败:", error);
    showToast('获取科室列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 定义跳转方法，携带科室信息
const goToDoctorSelector = (department) => {
  router.push({
    path: '/selectDoctor',
    query: { department: department }
  });
};

// 组件挂载时获取科室列表
onMounted(() => {
  fetchDepartments();
});
</script>

<style scoped>
.swipe-container {
  min-height: 200px;
}

.grid-text {
  font-size: 14px;
  color: #333;
}

.van-grid-item {
  padding: 10px 0;
}
</style>
